﻿using System;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Web.UI.WebControls.WebParts;
using System.Linq;
using Microsoft.SharePoint.WebControls;
using System.Web;
using Microsoft.SharePoint;
using SlamCms.Data;
using SlamCms.SharePoint.Core;

namespace SlamCms.SharePoint.Tagging.WebParts
{
	public partial class TagManagerUserControl : UserControl
	{
		private string _tagCategoryNewFormUrl;
		private string _tagCategoryEditFormUrl;
		private string _tagNewFormUrl;
		private string _tagEditFormUrl;

		public string TagCategoryNewFormUrl
		{
			get
			{
				if (String.IsNullOrEmpty(_tagCategoryNewFormUrl))
				{
					LoadFormUrls();
				}
				return _tagCategoryNewFormUrl;
			}
		}

		public string TagCategoryEditFormUrl
		{
			get
			{
				if (String.IsNullOrEmpty(_tagCategoryEditFormUrl))
				{
					LoadFormUrls();
				}
				return _tagCategoryEditFormUrl;
			}
		}

		public string TagNewFormUrl
		{
			get
			{
				if (String.IsNullOrEmpty(_tagNewFormUrl))
				{
					LoadFormUrls();
				}
				return _tagNewFormUrl;
			}
		}


		public string TagEditFormUrl 
		{
			get
			{
				if (String.IsNullOrEmpty(_tagEditFormUrl))
				{
					LoadFormUrls();
				}
				return _tagEditFormUrl;
			}
		}

		private void LoadFormUrls()
		{
			SPSite site = SPControl.GetContextSite(HttpContext.Current);
			SPSecurity.RunWithElevatedPrivileges(delegate()
			{
				using (SPSite elevatedSite = new SPSite(site.ID))
				{
					SPWeb globalSettingsWeb = elevatedSite.AllWebs.ToList().Where(w => w.Name.Equals("GlobalSettings")).FirstOrDefault();
					if (globalSettingsWeb != null)
					{
						SPList tagCategoryList = globalSettingsWeb.Lists["Tag Categories"];
						_tagCategoryNewFormUrl = tagCategoryList.NavigateForFormsPages ? tagCategoryList.Forms[PAGETYPE.PAGE_NEWFORM].Url : GetDialogScript(globalSettingsWeb.ServerRelativeUrl, tagCategoryList.Forms[PAGETYPE.PAGE_NEWFORM].Url);
						_tagCategoryEditFormUrl = tagCategoryList.NavigateForFormsPages ? tagCategoryList.Forms[PAGETYPE.PAGE_EDITFORM].Url : GetDialogScript(globalSettingsWeb.ServerRelativeUrl, tagCategoryList.Forms[PAGETYPE.PAGE_EDITFORM].Url);

						SPList tagList = globalSettingsWeb.Lists["Tags"];
						_tagNewFormUrl = tagList.NavigateForFormsPages ? tagList.Forms[PAGETYPE.PAGE_NEWFORM].Url : GetDialogScript(globalSettingsWeb.ServerRelativeUrl, tagList.Forms[PAGETYPE.PAGE_NEWFORM].Url);
						_tagEditFormUrl = tagList.NavigateForFormsPages ? tagList.Forms[PAGETYPE.PAGE_EDITFORM].Url : GetDialogScript(globalSettingsWeb.ServerRelativeUrl, tagList.Forms[PAGETYPE.PAGE_EDITFORM].Url);

						globalSettingsWeb.Dispose();
					}
				}
			});
		}


		private string GetDialogScript(string siteUrl, string formUrl)
		{
			return String.Format("openFormDialog('{0}/{1}');", siteUrl.TrimEnd('/'), formUrl.TrimStart('/'));
		}

		protected void Page_Load(object sender, EventArgs e)
		{
			if (!IsPostBack)
			{
				SPWeb site = SPControl.GetContextWeb(HttpContext.Current);

				Page.ClientScript.RegisterClientScriptInclude("jquery", ResolveUrl("~/_layouts/inc/jquery-1.6.2.min.js"));
				Page.ClientScript.RegisterClientScriptInclude("jquery.ui.core", ResolveUrl("~/_layouts/inc/jquery.ui.core.js"));
				Page.ClientScript.RegisterClientScriptInclude("jquery.ui.widget", ResolveUrl("~/_layouts/inc/jquery.ui.widget.js"));
				Page.ClientScript.RegisterClientScriptInclude("jquery.ui.position", ResolveUrl("~/_layouts/inc/jquery.ui.position.js"));
				Page.ClientScript.RegisterClientScriptInclude("jquery.ui.mouse", ResolveUrl("~/_layouts/inc/jquery.ui.mouse.js"));
				Page.ClientScript.RegisterClientScriptInclude("jquery.ui.autocomplete", ResolveUrl("~/_layouts/inc/jquery.ui.autocomplete.js"));
				Page.ClientScript.RegisterClientScriptInclude("jquery.ui.draggable", ResolveUrl("~/_layouts/inc/jquery.ui.draggable.js"));
				Page.ClientScript.RegisterClientScriptInclude("jquery.ui.droppable", ResolveUrl("~/_layouts/inc/jquery.ui.droppable.js"));
				Page.ClientScript.RegisterClientScriptInclude("jquery.ui.resizable", ResolveUrl("~/_layouts/inc/jquery.ui.resizable.js"));
				Page.ClientScript.RegisterClientScriptInclude("jquery.ui.selectable", ResolveUrl("~/_layouts/inc/jquery.ui.selectable.js"));
				Page.ClientScript.RegisterClientScriptInclude("jquery.ui.sortable", ResolveUrl("~/_layouts/inc/jquery.ui.sortable.js"));
				Page.ClientScript.RegisterClientScriptInclude("jquery.cookie", ResolveUrl("~/_layouts/inc/jquery.cookie.js"));
				Page.ClientScript.RegisterClientScriptInclude("jquery.dynatree", ResolveUrl("~/_layouts/inc/jquery.dynatree.min.js"));
				Page.ClientScript.RegisterClientScriptInclude("jquery.contextMenu", ResolveUrl("~/_layouts/inc/jquery.contextMenu-custom.js"));
				Page.ClientScript.RegisterClientScriptInclude("jquery.blockUI", ResolveUrl("~/_layouts/inc/jquery.blockUI.js"));
				Page.ClientScript.RegisterClientScriptInclude("tagmanager", ResolveUrl("~/_layouts/inc/slamcms.tagging.tagmanager.js"));

				AddCssInclude("~/_layouts/1033/STYLES/SlamCms.Tagging.TagManager.css");

				Page.ClientScript.RegisterStartupScript(typeof(Page), "SetTagManagerServiceLocation", String.Format("tagManagerServiceUrl = '{0}/_vti_bin/TagTreeManagerService.svc';", site.ServerRelativeUrl.TrimEnd('/')), true);

				tagTreeList.DataSource = SlamCmsContext.Data.TagTrees.OrderBy(t => t.SortOrder);
				tagTreeList.DataTextField = "Title";
				tagTreeList.DataValueField = "TagTreeId";
				tagTreeList.DataBind();

				if (Request.QueryString["tree"] != null)
				{
					tagTreeListValue.Text = Request.QueryString["tree"];
					ListItem item = tagTreeList.Items.FindByValue(Request.QueryString["tree"]);
					if (item != null)
						item.Selected = true;
				}
				else
				{
					tagTreeList.SelectedIndex = 0;
					Response.Redirect(Request.Url.AbsolutePath + "?tree=" + tagTreeList.SelectedValue);
				}
			}
		}

		protected void tagTreeList_SelectedIndexChanged(object sender, EventArgs e)
		{
			Response.Redirect(Request.Url.AbsolutePath + "?tree=" + tagTreeList.SelectedValue);
		}

		private void AddCssInclude(string url)
		{
			string include = String.Format("<link rel=\"stylesheet\" type=\"text/css\" href=\"{0}\" media=\"all\" />", ResolveUrl(url));
			if (!Page.Header.Controls.Cast<Control>().OfType<LiteralControl>().Any(c => c.Text == include))
			{
				Page.Header.Controls.Add(new LiteralControl(include));
			}
		}

		private void AddJavascriptInclude(string url)
		{
			string include = String.Format("<script type=\"text/javascript\" language=\"javascript\" src=\"{0}\"></script>", ResolveUrl(url));
			if (!Page.Header.Controls.Cast<Control>().OfType<LiteralControl>().Any(c => c.Text == include))
			{
				Page.Header.Controls.Add(new LiteralControl(include));
			}
		}
	}
}
